package com.gopay.scheduler.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.cache.client.RedisClient;
import com.gopay.common.constants.dps.DpsStaCode;
import com.gopay.common.constants.dps.WaTyyPurchaseStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.constants.wallet.childTranType.BounsCommonConstants;
import com.gopay.common.constants.wallet.childTranType.Wallet01608ChildTranType;
import com.gopay.common.cps.dao.acct.CommonQueryDAO;
import com.gopay.common.cps.dao.wallet.bouns.WaBounsDetailOrderDao;
import com.gopay.common.cps.dao.wallet.bouns.WaBounsMainOrderDao;
import com.gopay.common.cps.dao.wallet.prepaid.WaPrepaidOrderDtlDao;
import com.gopay.common.cps.dao.wallet.tyy.WaTYYProductDao;
import com.gopay.common.cps.dao.wallet.tyy.WaTyyBizOrderDtlDao;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.domain.cps.wallet.Wallet01610VO;
import com.gopay.common.domain.dps.WaBounsDetailOrder;
import com.gopay.common.domain.dps.WaBounsMainOrder;
import com.gopay.common.domain.dps.WaPrepaidOrderDtl;
import com.gopay.common.domain.dps.WaTyyBizOrderDtl;
import com.gopay.common.domain.dps.WaTyyProduct;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.cron.web.util.CallCPSUtil;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.dao.CpsGenMainOrderReadDao;

/**
 * 修改主订单状态
 * 创建时间超过24小时，订单处理码为1000
 * 红包超过24小时未领取
 * @author LEI XIAOBAO
 * @date 2015年12月1日
 */
public class UpdateWalletOrderStatusJob extends GopayBaseJob {

	private Logger logger = LoggerFactory.getLogger(UpdateWalletOrderStatusJob.class);
	
	private CpsGenMainOrderReadDao cpsGenMainOrderReadDao;
	
	private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;
	
	@Resource(name = "cpsGenMainOrderReadDao")
	public void setCpsGenMainOrderReadDao(CpsGenMainOrderReadDao cpsGenMainOrderReadDao) {
		this.cpsGenMainOrderReadDao = cpsGenMainOrderReadDao;
	}

	@Resource(name = "cpsGeneralMainOrderOperClient")
	public void setCpsGeneralMainOrderOperClient(MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
		this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
	}
    @Resource(name = "waTYYProductDao")
    private WaTYYProductDao waTYYProductDao;
    
    @Resource(name = "waBounsMainOrderDao")
    private WaBounsMainOrderDao waBounsMainOrderDao;
    
    @Resource(name = "waBounsDetailOrderDao")
	private WaBounsDetailOrderDao waBounsDetailOrderDao;
    
    @Resource(name = "comQueryDao")
    private CommonQueryDAO comQueryDao;
    
	@Resource(name = "waPrepaidOrderDtlDao")
	private WaPrepaidOrderDtlDao waPrepaidOrderDtlDao;
    
	@Resource(name="waTyyBizOrderDtlDao")
	private WaTyyBizOrderDtlDao waTyyBizOrderDtlDao;
	
	@Override
	protected void doJobInternal() {
		logger.error("updateWalletOrderStatusJob------------start---------");
		List<CpsGenMainOrder> list = cpsGenMainOrderReadDao.findTimeoutOrdersByCreateTimeAndProcessCode(String.valueOf(TxnStaCode.TXN_STA_CD_30401.value));
	    //天溢赢待付款半小时失效
		List<CpsGenMainOrder> listTyy = cpsGenMainOrderReadDao.findTimeoutTyyOrdersByCreateTimeAndProcessCode(String.valueOf(TxnStaCode.TXN_STA_CD_30401.value));
	    //天溢赢银行处理中1天之后订单失效
		List<Integer> txnStaCodeList = new ArrayList<Integer>();
		txnStaCodeList.add(TxnStaCode.TXN_STA_CD_30000.value);//天溢盈增加30000状态的订单失效轮训 modify by tangyang at 20170321 
		txnStaCodeList.add(TxnStaCode.TXN_STA_CD_30101.value);
		List<CpsGenMainOrder> listTyyBank = cpsGenMainOrderReadDao.findBankTimeoutTyyOrdersByCreateTimeAndProcessCode(txnStaCodeList);
        if (!(null == listTyy) && !(0 == listTyy.size())) {
            list.addAll(listTyy);
        }
        if (!(null == listTyyBank) && !(0 == listTyyBank.size())) {
            list.addAll(listTyyBank);
        }
	    if( list != null && list.size() > 0 ){
			logger.error("查询获取到的订单数： "+list.size());
		}
		int successCount = 0;
		for (CpsGenMainOrder cpsGenMainOrder : list) {
			Map<MainOrderField, String> values = new HashMap<MainOrderField, String>();
			String gopayOrderId = cpsGenMainOrder.getGopayOrderId();
			try {
				successCount++;
				logger.info("第"+successCount+"条修改成功,gopayOrderId: "+gopayOrderId+",TxnStaCode:"+cpsGenMainOrder.getTxnStaCd());
				values.put(MainOrderField.TXN_STA_CD, TxnStaCode.TXN_STA_CD_20002.value+"");
				values.put(MainOrderField.TRAN_FINISH_TIME, DateUtils.getCurrDate());
				values.put(MainOrderField.ERR_MSG, "订单已过期");
				cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, values);
				/*--------跟主订单状体同步 30401->20002 红包/三充 add by zhoupeng 20170512 start-----*/
				if (IntTxnCd._01608.value.equals(cpsGenMainOrder.getGopayIntTxnCd())) {
					WaBounsMainOrder waBounsMainOrder =waBounsMainOrderDao.queryByGopayOrderId(gopayOrderId);
					waBounsMainOrder.setBounsStaCd(DpsStaCode.DPS_STA_CD_20002.value);
					waBounsMainOrder.setUpdateTime(new Date());
					waBounsMainOrderDao.update(waBounsMainOrder);
				}else if(IntTxnCd._01611.value.equals(cpsGenMainOrder.getGopayIntTxnCd())
						|| IntTxnCd._01612.value.equals(cpsGenMainOrder.getGopayIntTxnCd())
						|| IntTxnCd._01613.value.equals(cpsGenMainOrder.getGopayIntTxnCd())
						|| IntTxnCd._01618.value.equals(cpsGenMainOrder.getGopayIntTxnCd())){//add by zhoupeng 21170628
					WaPrepaidOrderDtl pOrderDtl = waPrepaidOrderDtlDao.find(WaPrepaidOrderDtl.class, gopayOrderId);
					pOrderDtl.setRechargeStatus(DpsStaCode.DPS_STA_CD_20002.value);
					pOrderDtl.setUpdateTs(new Date());
					waPrepaidOrderDtlDao.update(pOrderDtl);
				/*--------跟主订单状体同步 30401->20002 红包/三充 add by zhoupeng 20170512 end-----*/
				}else if (IntTxnCd._01615.value.equals(cpsGenMainOrder.getGopayIntTxnCd())) {
                    logger.info("-----------------额度还原start----------------");
                    //增加业务表购买状态为失效 modify by tangyang at 20170526
                    Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("purchaseGopayOrderId", gopayOrderId);
					List<WaTyyBizOrderDtl> bizOrderDtls = waTyyBizOrderDtlDao.getOrderDtlByCondition(paramMap);
					if( bizOrderDtls != null && bizOrderDtls.size() > 0 ){
						WaTyyBizOrderDtl waTyyBizorderDtl = bizOrderDtls.get(0);
						waTyyBizorderDtl.setPurchaseStatus(WaTyyPurchaseStatus.TYY_PURCHASE_STA_CD_20002.value);
						waTyyBizOrderDtlDao.update(waTyyBizorderDtl);
					}
                    String pdId = cpsGenMainOrder.getRemark1();// 获取产品Id
                    WaTyyProduct waTYYProduct = waTYYProductDao.getProductById(pdId);
                    // 还原未结算额度（原未结算-订单交易金额）
//                    waTYYProduct
//                            .setUnsettleAmt(waTYYProduct.getUnsettleAmt().subtract(cpsGenMainOrder.getOrderDealAmt()));
                    // 还原可购买额度（可购买额度+订单交易金额）
                    waTYYProduct.setAvaAmt(waTYYProduct.getAvaAmt().add(cpsGenMainOrder.getOrderDealAmt()));
                    waTYYProductDao.update(waTYYProduct);
                    logger.info("---UnsettleAmt" + waTYYProduct.getUnsettleAmt() + "AvaAmt" + waTYYProduct.getAvaAmt());
                    logger.info("-----------------额度还原end----------------");
                }
			} catch (GopayException e) {
				logger.error("update order status fail,orderId:" + gopayOrderId);
				logger.error(e.getMessage());
			} catch (Exception e) {
				logger.error("update order status fail,orderId:" + gopayOrderId);
				logger.error(e.getMessage());
			}
		}
		logger.error("修改成功的订单数： "+successCount);
		logger.error("updateWalletOrderStatusJob------------end---------");
		
		
		logger.error("catchBouns updateWalletOrderStatusJob------------start---------");
		List<CpsGenMainOrder> mainOrderList = cpsGenMainOrderReadDao.findTimeoutOrdersByCreateTimeAndProcessCode(String.valueOf(TxnStaCode.TXN_STA_CD_30402.value));
		//得到红包30402并超过一天的订单 add by zhoupeng 20170522
		List<CpsGenMainOrder> bounsList30402=cpsGenMainOrderReadDao.findTimeoutBounsOrdersByCreateTime(String.valueOf(TxnStaCode.TXN_STA_CD_30402.value));
		if(bounsList30402 != null && bounsList30402.size()>0){
			mainOrderList.removeAll(bounsList30402);//防止两次查询出现重复订单
			mainOrderList.addAll(bounsList30402);
        }
		if( mainOrderList != null && mainOrderList.size() > 0 ){
			logger.error("catchBouns 查询获取到的订单数： "+mainOrderList.size());
		}
		int catchBounsCount = 0;
		for (CpsGenMainOrder cpsGenMainOrder : mainOrderList) {
			Map<MainOrderField, String> values = new HashMap<MainOrderField, String>();
			String gopayOrderId = cpsGenMainOrder.getGopayOrderId();
			try {
				if( cpsGenMainOrder.getGopayIntTxnCd().equals(IntTxnCd._01608.value) ){
					//删除redis口令红包队列 zhoupeng 2017-1-11
					WaBounsMainOrder waBounsMainOrder = waBounsMainOrderDao.queryByGopayOrderId(gopayOrderId);
					if (waBounsMainOrder != null && Wallet01608ChildTranType.BOUNS_TYPE_PASSWORD.equals(waBounsMainOrder.getBounsType())) {
						String bounsWord=waBounsMainOrder.getBounsWord();
						RedisClient.deleteKeyPrefix("{"+bounsWord+"}");
						logger.info("删除redis口令红包队列，口令为："+bounsWord);
					}
					Wallet01610VO wallet01610 = new Wallet01610VO();
					wallet01610.setBounsOrderId(gopayOrderId);
					CPSResponse response = CallCPSUtil.callByVOTicket(wallet01610);
					if( ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode()) ){
						waBounsMainOrder = waBounsMainOrderDao.queryByGopayOrderId(gopayOrderId);
						if (waBounsMainOrder != null) {
							//口令红包退款更新红包主表状态30-已失效，3-领取结束 add by zhoupeng 2017-1-9
							if (cpsGenMainOrder.getChildTranType().equals(Wallet01608ChildTranType.BOUNS_TYPE_PASSWORD)) {
									waBounsMainOrder.setWordStatus(BounsCommonConstants.DISABLE);
									waBounsMainOrder.setBounsStatus(BounsCommonConstants.SENDRECEIVEEND);
									
									//试算最佳红包
									WaBounsDetailOrder bestDetail=waBounsDetailOrderDao.findBestLuckByBounsMainOrderId(waBounsMainOrder.getBounsMainOrderId().toString());
									if(bestDetail!=null){
										bestDetail.setRecvBounsMax(BounsCommonConstants.RECV_BOUNS_MAX);
										bestDetail.setRecvBounsMaxDesc(getRecvBounsMaxDesc());
										bestDetail.setUpdateTime(DateUtils.getSystemDate());
										waBounsDetailOrderDao.update(bestDetail);
									}
							}
							waBounsMainOrder.setBounsStaCd(DpsStaCode.DPS_STA_CD_20005.value);//有退款 20005 add by zhoupeng 20170517
							waBounsMainOrder.setUpdateTime(new Date());
							waBounsMainOrderDao.update(waBounsMainOrder);
						}
						catchBounsCount ++;
					}
					logger.info("第"+catchBounsCount+"条callCPS wallet01610VO修改成功,orderId: "+gopayOrderId);
				}
				//modify by leixiaobao 2016-09-12，手机转账到银行，手机信用卡还款订单状态待付款，不修改订单状态。
				if( IntTxnCd._01605.value.equals(cpsGenMainOrder.getGopayIntTxnCd()) 
					|| IntTxnCd._01606.value.equals(cpsGenMainOrder.getGopayIntTxnCd()) 
					|| IntTxnCd._01617.value.equals(cpsGenMainOrder.getGopayIntTxnCd()))continue;//add by zhoupeng 01617兑付到银行的存在30402状态（自动结算失败，生成现在付款包）不更新
				if (!cpsGenMainOrder.getGopayIntTxnCd().equals(IntTxnCd._01608.value)
						|| (cpsGenMainOrder.getGopayIntTxnCd().equals(IntTxnCd._01608.value) && cpsGenMainOrder.getTxnStaCd()==TxnStaCode.TXN_STA_CD_30402.value)) {//兼容上线前后数据差异，防止重复退款add by zhoupeng 20170601
					values.put(MainOrderField.TXN_STA_CD, TxnStaCode.TXN_STA_CD_90502.value + "");
					cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, values);
				}
			} catch (GopayException e) {
				logger.error("update order status fail,orderId:" + gopayOrderId,e);
				logger.error(e.getMessage());
			} catch (Exception e) {
				logger.error("update order status fail,orderId:" + gopayOrderId,e);
				logger.error(e.getMessage());
			}
		}
		logger.error("catchBouns updateWalletOrderStatusJob------------end---------");
		
		logger.error("更新已领完的口令红包主业务表状态------------start---------");
		List<Object[]> bounsMainOrderList = queryMainOrder();
		if (bounsMainOrderList != null && bounsMainOrderList.size() > 0) {
			for (int i = 0; i < bounsMainOrderList.size(); i++) {
				Object[] gopayOrder = bounsMainOrderList.get(i);
				String gopayOrderId = (String) gopayOrder[0];
				//------------------测试使用fordebug---start-----
//				DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//				String dateStr = "2017/01/14 14:15:00";//fordebug
//				Date date = new Date();
//				try {
//					date = sdf.parse(dateStr);
//				} catch (ParseException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				long twelve=date.getTime();
				//------------------测试使用fordebug---end-----
				Date created_Ts = (Date) gopayOrder[1];
				long current = created_Ts.getTime();// 创建时间毫秒数
				long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();// 创建时间那天的零点零分零秒的毫秒数
				long twelve = zero + 24 * 60 * 60 * 1000 - 1;// 创建时间那天23点59分59秒的毫秒数
				Date dat = new Date();
				if (dat.getTime() > twelve) {//每个自然日更新状态
					WaBounsMainOrder waBounsMainOrder = waBounsMainOrderDao.queryByGopayOrderId(gopayOrderId);
					if (waBounsMainOrder != null) {
						List<WaBounsDetailOrder> WaBounsDetailOrderList = waBounsDetailOrderDao
								.findbyBounsMainOrderId(waBounsMainOrder.getBounsMainOrderId());
						// 清除redis已领红包人缓存
						if (WaBounsDetailOrderList != null) {
							for (WaBounsDetailOrder WaBounsDetailOrder : WaBounsDetailOrderList) {
								RedisClient.hdel("{" + WaBounsDetailOrder.getBounsWord() + "}:usedCustId",
										WaBounsDetailOrder.getRecvCustId());
								logger.info("清除redis已领红包CustId缓存，口令为:" + WaBounsDetailOrder.getBounsWord() + ",CustId为:"
										+ WaBounsDetailOrder.getRecvCustId());
							}
						}
						waBounsMainOrder.setWordStatus(BounsCommonConstants.DISABLE);
						waBounsMainOrder.setUpdateTime(DateUtils.getSystemDate());
						waBounsMainOrderDao.update(waBounsMainOrder);
					}
					
					
				}
			}
		}
		logger.error("更新已领完的口令红包主业务表状态------------end---------");
	}

	
	private String getRecvBounsMaxDesc(){
		String FristFlagStr[] = new String[] { "福星高照", "鸿运当头", "颜值担当",
				"人品爆发", "手气最佳", "富贵花开", "财运亨通", "无人争锋", "锐不可当", "唯我独尊", "所向披靡",
				"举世无双", "朕钦点的" };
		int resule = (int) (Math.random() * FristFlagStr.length);
		return FristFlagStr[resule];
	}
	
	/**
	 * 查询已领完的口令红包gopay_order_id,created_Ts
	 * @return
	 */
	private List<Object[]> queryMainOrder() {
		StringBuffer sql = new StringBuffer();
		sql.append(" select r.gopay_order_id,c.created_Ts from Wa_Bouns_Main_Order r ");
		sql.append("  left join CPS_GEN_MAIN_ORDER c ");
		sql.append("  on r.gopay_order_id = c.gopay_order_id ");
		sql.append("  where r.word_status =:wordstatus ");
		sql.append("  and (r.bouns_status =:bounsstatus or r.bouns_status =:bounsstatusone)");
		sql.append("  and c.child_tran_type =:childTranType ");
		sql.append("  and c.gopay_int_txn_cd =:IntTxnCd01608 ");
		sql.append("  and c.txn_sta_cd =:TxnStaCd20000 ");

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("wordstatus", BounsCommonConstants.USABLE);
		param.put("bounsstatus", BounsCommonConstants.SENDRECEIVESUCCESS);
		param.put("bounsstatusone", BounsCommonConstants.SENDAWAIT);
		param.put("IntTxnCd01608", IntTxnCd._01608.value);
		param.put("TxnStaCd20000", TxnStaCode.TXN_STA_CD_20000.value);
		param.put("childTranType", Wallet01608ChildTranType.BOUNS_TYPE_PASSWORD);

		List<Object[]> waBounsMainOrder = comQueryDao.findBySql(sql.toString(), param);
		logger.info("queryMainOrder()查询已领完的口令红包SQL："+sql.toString()+"param为:"+param);
		return waBounsMainOrder;
	}
}
